import axios from 'axios'

const API_URL = process.env.VUE_APP_API_URL || 'http://localhost:3000/api'

const state = {
  applications: [],
  myApplications: [],
  adoptedPets: [],
  adoptionRecords: [],
  currentApplication: null,
  pagination: {
    total: 0,
    page: 1,
    limit: 10,
    totalPages: 0
  }
}

const mutations = {
  SET_APPLICATIONS(state, { applications, pagination }) {
    state.applications = applications
    state.pagination = pagination
  },
  SET_MY_APPLICATIONS(state, applications) {
    state.myApplications = applications
  },
  SET_ADOPTED_PETS(state, pets) {
    state.adoptedPets = pets
  },
  SET_ADOPTION_RECORDS(state, { records, pagination }) {
    state.adoptionRecords = records
    state.pagination = pagination
  },
  SET_CURRENT_APPLICATION(state, application) {
    state.currentApplication = application
  },
  ADD_APPLICATION(state, application) {
    state.myApplications.unshift(application)
  },
  UPDATE_APPLICATION_STATUS(state, { id, status }) {
    // 更新管理员的应用列表
    const appIndex = state.applications.findIndex(app => app.id === id)
    if (appIndex !== -1) {
      state.applications[appIndex].status = status
    }
    
    // 更新用户的应用列表
    const myAppIndex = state.myApplications.findIndex(app => app.id === id)
    if (myAppIndex !== -1) {
      state.myApplications[myAppIndex].status = status
    }
    
    // 更新当前应用
    if (state.currentApplication && state.currentApplication.id === id) {
      state.currentApplication.status = status
    }
  }
}

const actions = {
  // 提交领养申请
  async submitApplication({ commit, dispatch, rootGetters }, applicationData) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const config = {
        headers: { 'x-auth-token': rootGetters['auth/authHeader']['x-auth-token'] }
      }
      
      const response = await axios.post(`${API_URL}/adoptions/apply`, applicationData, config)
      
      commit('ADD_APPLICATION', response.data)
      return response.data
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return null
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 获取用户的领养申请
  async fetchMyApplications({ commit, dispatch, rootGetters }) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const config = {
        headers: { 'x-auth-token': rootGetters['auth/authHeader']['x-auth-token'] }
      }
      
      const response = await axios.get(`${API_URL}/adoptions/my-applications`, config)
      
      commit('SET_MY_APPLICATIONS', response.data)
      return response.data
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return []
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 获取用户已领养的宠物
  async fetchMyAdoptedPets({ commit, dispatch, rootGetters }) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const config = {
        headers: { 'x-auth-token': rootGetters['auth/authHeader']['x-auth-token'] }
      }
      
      const response = await axios.get(`${API_URL}/adoptions/my-pets`, config)
      
      commit('SET_ADOPTED_PETS', response.data)
      return response.data
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return []
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 获取单个申请详情
  async fetchApplication({ commit, dispatch, rootGetters }, applicationId) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const config = {
        headers: { 'x-auth-token': rootGetters['auth/authHeader']['x-auth-token'] }
      }
      
      const response = await axios.get(`${API_URL}/adoptions/applications/${applicationId}`, config)
      
      commit('SET_CURRENT_APPLICATION', response.data)
      return response.data
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return null
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 管理员获取所有申请
  async fetchAllApplications({ commit, dispatch, rootGetters }, { status = null, page = 1, limit = 10 }) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const config = {
        headers: { 'x-auth-token': rootGetters['auth/authHeader']['x-auth-token'] },
        params: { page, limit }
      }
      
      if (status) {
        config.params.status = status
      }
      
      const response = await axios.get(`${API_URL}/adoptions/applications`, config)
      
      commit('SET_APPLICATIONS', {
        applications: response.data.applications,
        pagination: response.data.pagination
      })
      return response.data.applications
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return []
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 管理员获取特定宠物的申请
  async fetchPetApplications({ dispatch, rootGetters }, petId) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const config = {
        headers: { 'x-auth-token': rootGetters['auth/authHeader']['x-auth-token'] }
      }
      
      const response = await axios.get(`${API_URL}/adoptions/pet/${petId}`, config)
      
      return response.data
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return []
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 管理员获取领养记录
  async fetchAdoptionRecords({ commit, dispatch, rootGetters }, { page = 1, limit = 10 }) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const config = {
        headers: { 'x-auth-token': rootGetters['auth/authHeader']['x-auth-token'] },
        params: { page, limit }
      }
      
      const response = await axios.get(`${API_URL}/adoptions/records`, config)
      
      commit('SET_ADOPTION_RECORDS', {
        records: response.data.records,
        pagination: response.data.pagination
      })
      return response.data.records
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return []
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 管理员更新申请状态
  async updateApplicationStatus({ commit, dispatch, rootGetters }, { applicationId, status }) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const config = {
        headers: { 'x-auth-token': rootGetters['auth/authHeader']['x-auth-token'] }
      }
      
      const response = await axios.put(
        `${API_URL}/adoptions/applications/${applicationId}`,
        { status },
        config
      )
      
      commit('UPDATE_APPLICATION_STATUS', { id: applicationId, status })
      return response.data
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return null
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  }
}

const getters = {
  getAllApplications: state => state.applications,
  getMyApplications: state => state.myApplications,
  getMyAdoptedPets: state => state.adoptedPets,
  getAdoptionRecords: state => state.adoptionRecords,
  getCurrentApplication: state => state.currentApplication,
  getPendingApplications: state => state.applications.filter(app => app.status === 'pending'),
  getApprovedApplications: state => state.applications.filter(app => app.status === 'approved'),
  getRejectedApplications: state => state.applications.filter(app => app.status === 'rejected'),
  getMyPendingApplications: state => state.myApplications.filter(app => app.status === 'pending'),
  getMyApprovedApplications: state => state.myApplications.filter(app => app.status === 'approved')
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 